/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils.Servers;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author killan
 */
public class SubManga extends ServerM {

    private URL url;
    private URLConnection urlConn;
    private InputStream is;
    private String globPath = "c:/imanga/", carp = "", linea = "", carpUrl = "";
    private File f, fo, f2, fd, fos;
    private BufferedReader br;
    private BufferedWriter bw;

    public SubManga() {
        try {
            url = new URL("http://submanga.com");
        } catch (Exception ex) {
        }
    }

    public void getSeries(String path) {
        //Descarga de Datos
        try {
            url = new URL("http://submanga.com/series");
            urlConn = url.openConnection();
            is = urlConn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));

            // Fichero en el que queremos guardar el contenido
            fos = new File(path + "Conf/seriesH.txt");
            bw = new BufferedWriter(new FileWriter(fos));

            //Buffer para ir leyendo.


            // Primera lectura y bucle hasta el final
            String linea2 = "";
            while ((linea2 = br.readLine()) != null) {
                bw.write(linea2);
                bw.newLine();
            }

            // Cierre de conexion y fichero.
            is.close();
            br.close();
            bw.close();
        } catch (Exception ex) {
        }
        //Generacion de Archivo .konf
        try {
            //Declaracion Ficheros de Datos
            f = new File(path + "Conf/seriesH.txt");
            fo = new File(path + "Conf/series.konf");
            //Declaraciones Buffers Lectura y Escritura
            br = new BufferedReader(new FileReader(f));
            bw = new BufferedWriter(new FileWriter(fo));
            //Comprobacion de que Existe f
            if (f.exists()) {
                //Leemos una Linea
                linea = br.readLine();
                int idx = 0, idx2 = 0;
                //Continua Leyendo hasta el Final
                while ((linea = br.readLine()) != null) {
                    idx = 0;
                    //Busca serie=
                    idx = linea.indexOf("td><a href=\"http://submanga.com/");
                    if (idx > 0) {
                        //Busca "
                        idx2 = linea.indexOf("\"", idx + 30);
                        //Escribe el Nombre de la Serie en el .konf
                        bw.write(linea.substring(idx + 32, idx2));
                        bw.newLine();
                    }
                }
            }
            br.close();
            bw.close();
            f.delete();
        } catch (Exception e) {
        }
    }

    public void getChaptersList(String path, String manga, String fanSub) {
        try {
            url = new URL("http://submanga.com/" + manga + "/" + fanSub);
            urlConn = url.openConnection();

            is = urlConn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));

            // Fichero en el que queremos guardar el contenido
            fos = new File(path + "Conf/MangaList/" + manga + "H.txt");
            bw = new BufferedWriter(new FileWriter(fos));

            //Buffer para ir leyendo.


            // Primera lectura y bucle hasta el final
            String linea2 = "";
            while ((linea2 = br.readLine()) != null) {
                bw.write(linea2);
                bw.newLine();
            }


            // Cierre de conexion y fichero.
            is.close();
            br.close();
            bw.close();
        } catch (Exception ex) {
        }
        //Generacion de Archivo .konf
        try {
            //Declaracion Ficheros de Datos
            fd = new File(path + "Conf/MangaList/");
            fd.mkdirs();
            f = new File(path + "Conf/MangaList/" + manga + "H.txt");
            fo = new File(path + "Conf/MangaList/" + manga + ".konf");
            //Declaraciones Buffers Lectura y Escritura
            br = new BufferedReader(new FileReader(f));
            bw = new BufferedWriter(new FileWriter(fo));
            //Comprobacion de que Existe f
            if (f.exists()) {
                //Leemos una Linea
                linea = br.readLine();
                int idx = 0, idx2 = 0;
                //Continua Leyendo hasta el Final
                while ((linea = br.readLine()) != null) {
                    idx = 0;
                    //Busca serie=
                    idx = linea.indexOf("a href=\"http://submanga.com/" + manga + "/");
                    if (idx > 0) {
                        //Busca "
                        int idx3 = manga.indexOf("_");
                        if (idx3 > 0) {
                            idx2 = linea.indexOf("\">" + manga.substring(0, idx3), idx);
                        } else {
                            idx2 = linea.indexOf("\">" + manga, idx);
                        }
                        //Escribe el Nombre de la Serie en el .konf
                        String l2 = linea.substring((idx + 28 + manga.length() + 1), idx2);
                        bw.write(l2);
                        bw.newLine();
                    }
                }
            }

            br.close();
            bw.close();
            f.delete();
        } catch (Exception e) {
        }
    }

    public void getPages(String manga, String Ch) {
        try {
            f2 = new File(globPath + "Conf/MangaList/" + manga + ".konf");
            br = new BufferedReader(new FileReader(f2));
            linea = "";
            while ((linea = br.readLine()) != null) {
                int idx = 0;
                idx = linea.indexOf("/");
                if (Ch.equals(linea.substring(0, idx))) {
                    carp = linea.substring(idx + 1);
                    break;
                }
            }
            br.close();
            url = new URL("http://submanga.com/c/" + carp);
            urlConn = url.openConnection();
            is = urlConn.getInputStream();

            br = new BufferedReader(new InputStreamReader(is));

            fo = new File(globPath + "Manga/" + manga + "/" + Ch);
            if (!fo.exists()) {
                fo.mkdirs();
            }
            fo = new File(globPath + "Manga/" + manga + "/" + Ch + "/" + carp + ".txt");
            if (!fo.exists()) {
                fo.createNewFile();
            }
            bw = new BufferedWriter(new FileWriter(fo));

            linea = "";
            while ((linea = br.readLine()) != null) {
                bw.write(linea);
                bw.newLine();
            }
            br.close();
            bw.close();
        } catch (Exception e) {
        }
        try {
            fo = new File(globPath + "Manga/" + manga + "/" + Ch + "/" + carp + ".txt");
            br = new BufferedReader(new FileReader(fo));
            while ((linea = br.readLine()) != null) {
                int idx = linea.indexOf("pages/");
                if (idx > 0) {
                    int idx2 = linea.indexOf("/1.jpg", idx);
                    carpUrl = linea.substring(idx + 6, idx2);
                    break;
                }
            }
            br.close();
        } catch (Exception e) {
        }

        getImages(manga, Ch, carpUrl);
    }

    public void getImages(String manga, String cap, String carpURL) {
        String path = globPath + "Manga/" + manga + "/" + cap + "/";
        File ft1, ft2, fd1, fdt[];
        fd1 = new File(path);
        fdt = fd1.listFiles();

        while (!((getNumPages(manga, cap) + 1) == fdt.length)) {
            for (int i = 1; i <= getNumPages(manga, cap); i++) {
                try {
                    ft1 = new File(path + i + ".jpg");
                    ft2 = new File(path + i + ".tx");
                    boolean estaCompleta = true;
                    if (ft1.exists() && ft2.exists()) {
                        estaCompleta = false;
                    } else if (!ft1.exists() && !ft2.exists()) {
                        estaCompleta = false;
                    } else if (ft1.exists() && !ft2.exists()) {
                        continue;
                    }
                    if (!estaCompleta) {
                        if (ft2.exists()) {
                            ft2.delete();
                        }
                        url = new URL("http://img.submanga.com:8080/pages/" + carpURL + "/" + i + ".jpg");
                        urlConn = url.openConnection();
                        // acceso al contenido web

                        is = urlConn.getInputStream();
                        // Fichero en el que queremos guardar el contenido
                        FileOutputStream fos2 = new FileOutputStream(path + i + ".tx");

                        // buffer para ir leyendo.
                        byte[] array = new byte[1024];

                        // Primera lectura y bucle hasta el final
                        int leido = is.read(array);
                        while (leido > 0) {
                            fos2.write(array, 0, leido);
                            leido = is.read(array);
                        }

                        // Cierre de conexion y fichero.
                        is.close();
                        fos2.close();
                        ft2.renameTo(ft1);
                    }
                } catch (Exception e) {
                }
            }
            fd1 = new File(path);
            fdt = fd1.listFiles();
        }
    }

    public int getNumPages(String manga, String Ch) {
        int pages = 0;
        out:
        try {
            f2 = new File(globPath + "Conf/MangaList/" + manga + ".konf");
            br = new BufferedReader(new FileReader(f2));
            linea = "";
            while ((linea = br.readLine()) != null) {
                int idx = 0;
                idx = linea.indexOf("/");
                if (Ch.equals(linea.substring(0, idx))) {
                    carp = linea.substring(idx + 1);
                    break;
                }
            }
            br.close();
            url = new URL("http://submanga.com/c/" + carp + "/" + 1);
            urlConn = url.openConnection();
            is = urlConn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            while ((linea = br.readLine()) != null) {
                int idx = linea.indexOf("n></");
                if (idx > 0) {
                    break;
                }
            }
            String l2[] = linea.split("\"");
            List pg = new ArrayList();
            for (String l3 : l2) {
                try {
                    pg.add(Integer.parseInt(l3));
                } catch (Exception e) {
                }
            }
            for (Object elem : pg) {
                if (elem instanceof Integer) {
                    Integer integer = (Integer) elem;
                    if (integer > pages) {
                        pages = integer;
                    }
                }
            }
            is.close();
        } catch (Exception e) {
            break out;
        }
        return pages;
    }
}
